import {Component, Input, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {BannerService} from '../banner.service';
import {Banner} from '../banner';
import {NzMessageService} from 'ng-zorro-antd';
import {Location} from '@angular/common';
import {ActivatedRoute} from '@angular/router';
import {MyimguploadComponent} from '@shared/myimgupload/myimgupload.component';
import {injectViewContainerRef} from '@angular/core/src/render3';

@Component({
    selector: 'app-add',
    templateUrl: './add.component.html',
})
export class AddComponent implements OnInit {

    bannerForm: FormGroup;

    banner: Banner = {};

    @ViewChild('imgload') myimgupload: MyimguploadComponent;

    constructor(
        private fb: FormBuilder,
        private bannerService: BannerService,
        private msgService: NzMessageService,
        private location: Location,
        private activityRoute: ActivatedRoute,

    ) {
    }

    ngOnInit() {
        this.bannerForm = this.fb.group({
            title: [''],
            url: [''],
            type: 0,
            img: ['', Validators.required],
        });

        const id = this.activityRoute.snapshot.paramMap.get('id');
        if (id) {
            this.bannerService.getBanner(id).subscribe(res => {
                this.banner = res;
                this.bannerForm.patchValue({
                    title: this.banner['title'],
                    url: this.banner['url'],
                    type: this.banner['type'],
                    img: this.banner['img'],
                });
                this.myimgupload.setImg(this.banner['img']);
                // this.banner['img'];
            });
        }
    }


    save() {
        // if (this.banner['img']) {
        //     this.msgService.warning('请上传图片');
        // }
        const res = this.bannerForm.value;
        this.banner['title'] = res['title'];
        this.banner['url'] = res['url'];
        this.banner['type'] = res['type'];
        this.banner['img'] = res['img'];
        this.bannerService.addBanner(this.banner).subscribe(__ => {
            this.location.back();
        }, __ => {

        });
    }

    uploadimg($event) {
        this.bannerForm.patchValue({
            img: $event,
        });
    }

}
